'use strict';
/**
 * @name 技术方案详情页面Controller
 * @author zyf
 */
angular.module('metalabPartnerApp')
    .controller('TechnologyDetailCtrl', ['$scope', '$location', '$stateParams', 'MetaResources', 'MetaRemind', 'MetaSEO',
        function ($scope, $location, $stateParams, MetaResources, MetaRemind, MetaSEO) {
            var favoriteObject;

            /**
             * 参数如果包含toVideo
             * 直接跳转到toVideo位置
             */
            if ($stateParams.toVideo) {
                setTimeout(function () {
                    window.scrollTo(0, document.getElementById("video").getBoundingClientRect().top + 50);
                }, 500);
            }

            /**
             * 从后端获取technology detail 信息
             */
            $scope.waitingDetailPromise = MetaResources.technology.get({
                'technologyId': $stateParams.technologyId,
                '_embed': 'leader'
            }, function (data) {
                $scope.techData = data;
                $scope.techData.templateUrl = 'myPopoverTemplate.html';
                $scope.hrefSrc = $location.absUrl();
                getRecommendData(data);
                HasFavorited();
                MetaSEO.setSEO(data.title, undefined, (data.areas ? (data.areas.concat(data.effectTags)).join(',') : ''));
            }, function (error) {
                MetaRemind.serverError(error);
            }).$promise;

            /**
             * @function 数据库请求相关技术方案列表
             */
            var getDataByQuery = function () {
                $scope.waitingArticlesPromise = MetaResources.technology.query({
                    _range: '1_10',
                    version: 'online',
                    online: true,
                    verified: true,
                    _sort: '-rank,-updatedAt'
                }, function (data) {
                    $scope.recommendData = data;
                }, function (err) {
                    MetaRemind.error(error);
                }).$promise;
            };

            /**
             * 顺便来一发推荐信息
             */
            var getRecommendData = function (data) {
                if (data.title) {
                    $scope.waitingArticlesPromise = MetaResources.search.website({
                        "_range": "1_10",
                        "type": "technology",
                        "version": "online",
                        "online": "true",
                        "verified": "true",
                        "searchText": data.title
                    }, function (data) {
                        if (data.length > 0) {
                            $scope.recommendData = data;
                        } else {
                            getDataByQuery();
                        }
                    }, function (error) {
                        MetaRemind.error(error);
                    }).$promise;
                } else {
                    getDataByQuery();
                }
            };

            /**
             * @function 是否已收藏
             */
            var HasFavorited = function () {
                MetaResources.favorite.exist({
                    'userId': '_self',
                    'targetId': $scope.techData.id
                }, function (data) {
                    $scope.isFavorited = true;
                    favoriteObject = data;
                }, function () {
                    $scope.isFavorited = false;
                });
            };

            /**
             * @function 收藏
             */
            $scope.Favorite = function () {
                if ($scope.isFavorited && favoriteObject) {
                    MetaResources.favorite.delete({
                        'id': favoriteObject.id
                    }, function () {
                        favoriteObject = null;
                        $scope.isFavorited = false;
                        MetaRemind.success('您已经取消收藏该技术方案');
                    }, function () {
                        MetaRemind.error('对不起，取消收藏失败，请稍后再试');
                    });
                } else {
                    MetaResources.favorite.add({
                        userId: '_self',
                        'targetId': $scope.techData.id,
                        'targetType': 'Technology'
                    }, null, function (success) {
                        favoriteObject = success;
                        $scope.isFavorited = true;
                        MetaRemind.success("收藏成功！");
                    }, function (err) {
                        console.log(err);
                        $scope.isFavorited = false;
                        MetaRemind.error("对不起，收藏失败！请稍后再试……");
                    });
                }
            }
        }]);

